package com.liu.mysqldemo.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.liu.mysqldemo.entity.Person;
import com.liu.mysqldemo.mapper.PersonMapper;
import com.liu.mysqldemo.service.PersonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@Slf4j
@RestController
public class PersonController {

    @Resource
    private PersonService personService;

    @GetMapping(value = "/findPersonByid",produces = {"application/json;charset=utf-8"})
    public String findPersonByid(Long id){
        Person person = personService.findPersonByid(id);
        log.info("findPersonByid:{}",JSON.toJSONString(person));
        return JSON.toJSONString(person);
    }

    @GetMapping(value = "/findPersonByname",produces = {"application/json;charset=utf-8"})
    public String findPersonByname(String name){
        Person person = personService.findPersonByName(name);
        log.info("findPersonByname:{}",JSON.toJSONString(person));//默认会去除null型属性

        return JSON.toJSONString(person, JSONWriter.Feature.WriteNulls);
    }

    @PostMapping(value = "/addPerson",produces = {"application/json;charset=utf-8"})
    public String addPerson(@RequestBody Person person){
        Person person1 = personService.addPerson(person);
        log.info("addPerson:{}",JSON.toJSONString(person1));
        return JSON.toJSONString(person1);
    }

    @PostMapping(value = "/addPerson1",produces = {"application/json;charset=utf-8"})
    public String addPerson1(String name,Integer age){
        Person pp = new Person();
        pp.setName(name);
        pp.setAge(age);
        Person person1 = personService.addPerson(pp);
        log.info("addPerson:{}",JSON.toJSONString(person1));
        return JSON.toJSONString(person1);
    }

    @PostMapping(value = "/updatePerson",produces = {"application/json;charset=utf-8"})
    public String updatePerson(@RequestBody Person person){
        person.setUpdatetime(System.currentTimeMillis());
        Person person1 = personService.updatePerson(person);
        log.info("updatePerson:{}",JSON.toJSONString(person1));
        return JSON.toJSONString(person1);
    }
}
